#include "widget.h"
#include "ui_widget.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QSizePolicy>
#include <QNetworkDatagram>
#include <QToolTip>
#include <QPushButton>

const QString& SERVER_IP = "127.0.0.1";
const quint16 SERVER_PORT = 8080;

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    socket = new QUdpSocket(this);

    this->setWindowTitle("远程信息提交");
    ui->lineEdit->setPlaceholderText("请输入文本...");
    QHBoxLayout* layout_h = new QHBoxLayout();
    QPushButton* button = new QPushButton();
    button->setText("发送");
    layout_h->addWidget(ui->lineEdit, 4);
    layout_h->addWidget(button, 1);
    ui->lineEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    button->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    QFont font;
    font.setPixelSize(20);
    ui->lineEdit->setFont(font);
    button->setFont(font);
    ui->listWidget->setFont(font);
    button->setToolTip("点击以向服务器发送");
    QVBoxLayout* layout_v = new QVBoxLayout();
    layout_v->addWidget(ui->listWidget, 5);
    layout_v->addLayout(layout_h, 1);
    this->setLayout(layout_v);

    connect(button, &QPushButton::clicked, this, &Widget::handle);

    connect(socket, &QUdpSocket::readyRead, this, &Widget::processResponse);
}

void Widget::handle()
{
    QString message = ui->lineEdit->text();
    QNetworkDatagram requestDatagram(message.toUtf8(), QHostAddress(SERVER_IP), SERVER_PORT);
    socket->writeDatagram(requestDatagram);
    ui->listWidget->addItem("已向服务器发送信息：" + message);
    ui->lineEdit->clear();
}

void Widget::processResponse()
{
    QNetworkDatagram responseDatagram = socket->receiveDatagram();
    QString response = responseDatagram.data();
    ui->listWidget->addItem("server says: " + response);
}

Widget::~Widget()
{
    delete ui;
}
